<?
require_once($r."_config/db.php");
require_once($r."_config/sms.php");
require_once($r."_config/site.php");
require_once($r."_engine/c_session.php");
require_once($r."_engine/c_monitor.php");
require_once($r."_engine/c_categories.php");
require_once($r."_engine/c_sql_table.php");
require_once($r."_engine/c_sp_gate.php");
require_once($r."_engine/functions.php");
require_once($r."_inc/text.php");

define("NEW_ACCOUNT_OK",					1);
define("NEW_ACCOUNT_ALREADY_EXIST",			2);
define("NEW_ACCOUNT_INCORRECT_PASSWORD2",	3);
define("NEW_ACCOUNT_INCORRECT_LOGIN",		4);
define("NEW_ACCOUNT_INCORRECT_EMAIL",		5);

$g_new_account_error_message_map = array(
	NEW_ACCOUNT_ALREADY_EXIST	=> $g_text_account_already_exist,
	NEW_ACCOUNT_INCORRECT_PASSWORD2	=> $g_text_incorrect_password2,
	NEW_ACCOUNT_INCORRECT_EMAIL	=> $g_text_incorrect_email,
);

$g_st_account = new CSqlTable("accounts", "id");
$g_st_account->field_types["created"]		= "dt";
$g_st_account->field_types["expire"]		= "dt";
$g_st_account->field_types["last_login"]	= "dt";
$g_st_account->field_types["current_login"]	= "dt";

class CAccount
{
	var $id, $data;
	var $categories;

	function CreateNew($quick_reg = false)
	{
		global $g_st_account;

		$this->InitNew();

		global $f_first_name, $f_email, $f_password;
		if (!$quick_reg)
		{
			$this->data["first_name"]	= $f_first_name;
			$this->data["password"]		= $f_password;
		}
		$this->data["email"]			= $f_email;

		global $f_timezone_offset, $g_datetime_is_dst;
		$this->data["timezone_offset"]	= $f_timezone_offset * 60;
		// Suppose that user has the same "daylight saving effect" as server has
		if ($g_datetime_is_dst) $this->data["timezone_offset"] -= 3600;

		// Check for correct e-mail address TODO
		if ($this->data["email"] == "") return NEW_ACCOUNT_INCORRECT_EMAIL;

		// Check if account already exist
		$query = "SELECT * FROM accounts WHERE UPPER(email)=UPPER('".$this->data["email"]."');";

		if ($g_st_account->SelectRow($query)) return NEW_ACCOUNT_ALREADY_EXIST;

		// Check if password do not match password2
		if (!$quick_reg)
		{
			global $f_password2;
			if ($this->data["password"] == "" ||
			    $this->data["password"] != $f_password2) return NEW_ACCOUNT_INCORRECT_PASSWORD2;
		}

		// Initialize account info
		$this->data["created"]			= gmt_time();
		$this->data["expire"]			= mktime(0,0,0,1,1,2038);
		$this->data["activation_code"]	= md5(uniqid(rand()));
		$this->data["activated"]		= 0;
		// TODO: use default plan for all accounts
		$this->data["plan_id"]			= 1;


		// Make default alert e-mail address like: "name <email>"
		$t = $this->data["email"];
		if (@$this->data["first_name"] != "")
			$t = $this->data["first_name"] . " <" . $t . ">";
		$this->data["def_alert_emails"] = $t;


		$g_st_account->Insert($this->data);
		$this->id = mysql_insert_id();
		//TODO: update plan field

		// Send email to user with activation link
		if (!$quick_reg)
		{
	        global $g_spg;
			$g_spg->SendEmail(array(
				"account_id"			=> $this->id,
				"email_content_type"	=> $this->data["def_alert_format"],
				"email_to"				=> $this->data["email"],
				"variables" => array(
					"first_name"		=> $this->data["first_name"],
					"activation_url"	=> $this->GetActivationURL(),
				),
				"email_template_name"	=> "account_activation",
			));
		}
		else
		{
			// TODO[KVV]: revise - add generated password
			$mail_message =
				"Hello, \n".
				"\n".
				"Thank you for registering with W3Monitor service. We have successfully ".
				"created an account for you to use W3Monitor service. You need to activate ".
				"your account before you can track web pages.\n".
				"\n".
				"Activation link: ".$this->GetActivationURL()."\n";
				"\n".
				"If you have any problems in activating your account, please send a mail to ".
				"support@w3monitor.com mentioning the email address used during registration.\n".
				"\n".
				"Regards\n".
				"With best regards W3Monitor\n".
				"http://www.w3monitor.com/\n";

			global $g_spg;
			$g_spg->SendEmail(array(
				"email_from" => "support@w3monitor.com",
				"email_to" => $this->data["email"],
				"email_subject" => "W3Monitor - account activation",
				"email_template" => $mail_message,
			));
		}

		// Send an email to the stats
		$this->NewAccountRegisteredStats();

		return NEW_ACCOUNT_OK;
	}

	function InitNew()
	{
		// Initialize account info
		$this->data = array();

		$this->data["last_login"]		= gmt_time();
		$this->data["current_login"]	= gmt_time();

		// Settings | General
		$this->data["def_frequency"]			= MONITOR_FREQUENCY_DAILY;
		global $g_hightlight_font_color_default;
		$this->data["def_highlight_font_color"]	= $g_hightlight_font_color_default;
		global $g_hightlight_bk_color_default;
		$this->data["def_highlight_bk_color"]	= $g_hightlight_bk_color_default;
		global $g_def_highlight_font_style;
		$this->data["def_highlight_font_style"]	= $g_def_highlight_font_style;

		// Settings | Notification
		$this->data["def_alert_format"]	= ALERT_FORMAT_HTML;
		global $g_alert_type_default;
		$this->data["def_alert_type"]	= $g_alert_type_default;

		// Settings | Display Options
		$this->data["view_max_size"]	= 50;

        // Other
		$this->data["email_bcc"]		= "";
	}

	function NewAccountRegisteredStats()
	{
		// Send an email to the stats with some minor user related info
		// (country, browser, etc.)

		global $r, $_SERVER, $anp_ip, $anp_cinfo;

		// IP to Country decoder
		$anp_path = $r."_engine/cr/";
		@require_once($anp_path."cr.php");
		@require_once($anp_path."countries.php");

		$anp_cinfo = get_cinfo($anp_country_code);

		$account_information =
			"-------------------------------------------\n".
			"User information\n".
			"Account ID:  ".@$this->id."\n".
			"First Name:  ".@$this->data["first_name"]."\n".
			"Last Name:   ".@$this->data["last_name"]."\n".
			"E-mail:      ".@$this->data["email"]."\n".
			"-------------------------------------------\n".
			"Browser information\n".
			"User agent:  ".@$_SERVER["HTTP_USER_AGENT"]."\n".
			"Remote addr: ".@$_SERVER["REMOTE_ADDR"]."\n".
			"Remote host: ".@$_SERVER["REMOTE_HOST"]."\n".
			"\n".
			"Information depends on IP address:"."\n".
			"IP:              ".$anp_ip."\n".
			"Country Code:    ".$anp_cinfo["code"]."\n".
			"Country Name:    ".$anp_cinfo["name"]."\n".
			"Region:          ".$anp_cinfo["region"]."\n".
			"Country Capital: ".$anp_cinfo["capital"]."\n".
			"Currency:        ".$anp_cinfo["currency"]."\n".
			"-------------------------------------------\n";

		global $g_spg;
		$g_spg->SendEmail(array(
			"email_template_name"	=> "new_account_stats",
			"email_content_type"	=> ALERT_FORMAT_PLAIN_TEXT,
			"variables" => array(
				"account_information"	=> $account_information,
			),
		));
	}

	function SaveTransparentSettings(&$monitor)
	{
		$list = array(
			"def_alert_type" => "alert_type",
		);

		$values = array();
		foreach ($list as $def_opt_name => $opt_name)
		{
			if (isset($monitor->data[$opt_name]))
				$values[$def_opt_name] = $monitor->data[$opt_name];
		}

		if (count($values) > 0)
		{
			$this->Update($values);
		}
	}

	function GetActivationURL()
	{
		global $g_site_root;
		$url = "http://".$g_site_root."/newcomers/signup_activation.php?".
			"id=".$this->id."&activation_code=".$this->data["activation_code"];
		return $url;
	}

	function Activate($activation_code)
	{
		if ($activation_code != $this->data["activation_code"]) {
			 die("Incorrect data.");
		}

		if ($this->data["activated"]) return;

		$this->Update(array("activated" => 1));

		// Create default monitor
		$m = new CMonitor();
		$c = new CCategories($this);

		global $g_site_root;
		$values = array(
			"url"			=> "http://".$g_site_root."/members/news.php",
			"title"			=> "W3M News - Changes Summary",
			"category_id"	=> $c->CreateNew("News"),
		);

		$m->CreateNew($this, $values);
	}

	function LoadById($id)
	{
		return $this->LoadByQuery(
			"SELECT * FROM accounts WHERE id='$id';"
		);
	}
	function LoadByEmail($email)
	{
		return $this->LoadByQuery(
			"SELECT * FROM accounts WHERE UPPER(email)=UPPER('$email')"
		);
	}
	function LoadByQuery($query)
	{
		global $g_st_account;
		$row = $g_st_account->SelectRow($query);
		if (!$row) return false;
		$this->LoadFromArray($row);
		return true;
	}

	function LoadFromArray($row)
	{
		foreach($row as $f => $v)
		{
			if (is_int($f)) continue;

			if ($f == "id")
				$this->id = $v;
			else
				$this->data[$f] = $v;
		}
	}

	function Update($values)
	{
		global $g_st_account;
		$this->LoadFromArray($values);
		return $g_st_account->Update($values, $this->id);
	}

	function TimeToUserTZ($dt)
	{
		$tz = @$this->data["timezone_offset"];

		$dt += $tz;

		global $g_datetime_is_dst;
		if ($g_datetime_is_dst) $dt += 3600;

		return $dt;
	}

	function GetExpire()
	{
		return @date("M j, Y",
			$this->TimeToUserTZ($this->data["expire"]));
	}
	function GetLastLogin()
	{
		return @date('M j, Y \a\t G:i',
			$this->TimeToUserTZ($this->data["last_login"]));
	}

	function GetMonitors($curr_page, $sort_field, $sort_order)
	{
        // view max size
		$vms = /*$this->data["view_max_size"]*/ 1000000;
        // view start position
        $vsp = (($curr_page-1) * $vms);

		$q = '
SELECT
    monitors.*, categories.name AS category_name,
    resources_storage.download_dt AS rs_download_dt,
    resources_storage.resource_status AS rs_resource_status
FROM monitors
LEFT JOIN categories ON (monitors.category_id = categories.id)
LEFT JOIN resources_storage_max_id ON (monitors.id = resources_storage_max_id.monitor_id)
LEFT JOIN resources_storage ON (resources_storage_max_id.max_id = resources_storage.id)
WHERE monitors.account_id = '.$this->id.'
ORDER BY '.$sort_field.' '.$sort_order.', id ASC
LIMIT '.$vsp.', '.$vms.';
        ';
		$res = execute_query($q);

		$ms = array();
		while ($row = @mysql_fetch_array($res))
		{
			global $g_st_monitor;
			$g_st_monitor->DecodeValues($row);

			$m = new CMonitor();
			$m->LoadFromArray($row);
			$ms[] = $m;
		}

		return $ms;
	}

	function CheckOwner(&$monitor)
	{
		// Check that monitor belongs to this account
		if ($this->id != $monitor->data["account_id"])
		{
			die("Access denied.");
		}
	}

	function GetCapabilityStats()
	{
		// changes detected in this month
		$res = execute_query('
			SELECT
				COUNT(*) AS cnt
			FROM
			    download_stats
			WHERE
				account_id = '.$this->id.' AND (
			    	resource_status = '.RESOURCE_STORAGE_STATUS_CHANGED.' OR
			    	resource_status = '.RESOURCE_STORAGE_STATUS_TRIGGERED.'
				) AND
				download_dt LIKE \''.date("Y-m-").'%\'
		');
		$row = @mysql_fetch_array($res);
		$result["month_changes"] = $row["cnt"];

		// current num of active monitors
		$res = execute_query('
			SELECT
				COUNT(*) AS cnt
			FROM
			    monitors
			WHERE
				account_id = '.$this->id.' AND
				status & '.MONITOR_STATUS_IS_ACTIVE_MASK.' = '.MONITOR_STATUS_IS_ACTIVE_MASK.'
		');
		$row = @mysql_fetch_array($res);
		$result["active_monitors"] = $row["cnt"];

		// max num of allowed active monitors with accont's plan
		$res = execute_query('
			SELECT
				plans.max_monitors AS cnt
			FROM
				accounts, plans
			WHERE
				accounts.id = '.$this->id.' AND
				accounts.plan_id = plans.id
		');
		$row = @mysql_fetch_array($res);
		$result["max_active_monitors"] = $row["cnt"];

		// num of additional monitors allowed to be activated
		$result["allowed_to_activate_monitors"] =
			$result["max_active_monitors"] - $result["active_monitors"];

		return $result;
	}
}


function RedirectToLogin($go_back = true)
{
	if ($go_back)
	{
		global $_SERVER;
		$ref = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] .
			"?" . $_SERVER["QUERY_STRING"];
		$ref = urlencode($ref);
	}
	else
	{
		$ref = "";
	}

	global $r;
	require_once($r."_engine/functions.php");
	generate_html_redirect($r."members/login.php".($go_back ? "?ref=$ref" : ""));
}

function GetActiveAccount($redirect_to_login=true)
{
	global $ses_account_id, $ses_login_password;

	$a = new CAccount();
	if (!$a->LoadById(@$ses_account_id) ||
		$a->data["password"] != @$ses_login_password)
	{
		if ($redirect_to_login) RedirectToLogin();
		return NULL;
	}

	global $g_session;
	if ($g_session->IsNewBrowserSession())
	{
		$a->Update(array(
			"last_login"	=> $a->data["current_login"],
			"current_login"	=> gmt_time(),
		));
	}

	return $a;
}

function SaveLoadViewParams(
	&$account,
	&$curr_page, &$total_items, &$total_pages,
	&$sort_field, &$sort_order)
{
	// page size
	$vms = $account->data["view_max_size"];

	// total items
	$q = "SELECT COUNT(id) AS cnt FROM monitors ".
		"WHERE monitors.account_id = '".$account->id."';";
	$row = @mysql_fetch_array($res = execute_query($q));
	$total_items = $row["cnt"];

	// total pages
	$total_pages = ceil($total_items / $vms);

	$a = array(
		array('n'=>"curr_page",		'm'=>"view_curr_page",		'd'=>1),
		array('n'=>"sort_field",	'm'=>"view_sort_field",		'd'=>"id"),
		array('n'=>"sort_order",	'm'=>"view_sort_order",		'd'=>"asc"));

	foreach($a as $ai)
	{
		$v = $ai['n'];

		if (!isset($$v)) {
			$$v = $account->data[$ai['m']];
			if (!isset($$v)) $$v = $ai['d'];
		}
		if ($$v != $account->data[$ai['m']]) {
			$account->Update(array($ai['m'] => $$v));
		}
	}

	if ($curr_page > $total_pages) $curr_page = $total_pages;
	if ($curr_page < 1) $curr_page = 1;
}
?>